package com.example.springai.tool;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.springai.bean.Course;
import com.example.springai.bean.CourseReservation;
import com.example.springai.bean.School;
import com.example.springai.bean.query.CourseQuery;
import com.example.springai.service.ICourseReservationService;
import com.example.springai.service.ICourseService;
import com.example.springai.service.ISchoolService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Insert;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Component
@RequiredArgsConstructor
public class CourseTools {

    private final ICourseService courseService;

    private final ISchoolService schoolService;

    private final ICourseReservationService courseReservationService;


    @Tool(description = "根据条件查询课程")
    public List<Course> queryCourses(@ToolParam(required = false, description = "课程查询条件") CourseQuery courseQuery){
        // [1] 如果查询条件为 null, 返回所有课程
        if(Objects.isNull(courseQuery)){
            return courseService.list();
        }

        // [2] 根据条件查询
        QueryChainWrapper<Course> wrapper = courseService.query()
                .eq(Objects.nonNull(courseQuery.getType()), "type", courseQuery.getType())
                .le(Objects.nonNull(courseQuery.getEdu()), "edu", courseQuery.getEdu());

        if(!CollectionUtils.isEmpty(courseQuery.getSorts())){
            for (CourseQuery.Sort sort : courseQuery.getSorts()) {
                wrapper.orderBy(true, sort.getAsc(), sort.getField());
            }
        }

        // [3] 返回查询结果
        return wrapper.list();
    }

    @Tool(description = "查询所有校区")
    public List<School> querySchools(){
        return schoolService.list();
    }


    @Tool(description = "生成课程预约单，并返回生成的预约单号")
    public Integer generateCourseReservation(@ToolParam(description = "预约课程") String course,
                                             @ToolParam(description = "学生姓名") String studentName,
                                             @ToolParam(description = "联系方式") String contactInfo,
                                             @ToolParam(description = "预约校区") String school,
                                             @ToolParam(description = "备注") String remark){

        CourseReservation courseReservation = new CourseReservation();
        courseReservation.setCourse(course);
        courseReservation.setStudentName(studentName);
        courseReservation.setContactInfo(contactInfo);
        courseReservation.setSchool(school);
        courseReservation.setRemark(remark);

        courseReservationService.save(courseReservation);
        return courseReservation.getId();
    }


}
